﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Eassets.Service.Global;
using Eassets.Layered.Domain.Global;
using Eassets.Service;
using Eassets.Layered.Domain;
using Eassets.Service.Asset;
using Eassets.Layered.Domain.Asset;
using System.Text.RegularExpressions;


namespace Eassets.UI.Asset
{
    public partial class AssetProcurementForm : System.Web.UI.Page
    {

        private DataTable tb;
        private string actionStatus = "Load";
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!Page.IsPostBack)
            {
                textBoxUnitCost.Attributes.Add("onkeypress", "javascript:return handleNumbersOnly(event,this)");
                textBoxQuantity.Attributes.Add("onkeypress", "javascript:return handleNumbersOnly(event,this)");
                textBoxTotalCost.Attributes.Add("onkeypress", "javascript:return handleNumbersOnly(event,this)");

                GetAllMainCategory();

                GetOrganizationLevelList();
                GetSuppliers();
                DisableComponents();
                string parameters = Request.QueryString.Get("Parameter");
                if (parameters != null)
                {
                    Regex regex = new Regex(";");
                    string[] arrayParameters = regex.Split(parameters);

                    long mainCategoryId = Convert.ToInt64(arrayParameters[1]);
                    long subCategoryId = Convert.ToInt64(arrayParameters[2]);
                    // long assetId = Convert.ToInt64(arrayParameters[5]);


                    CategoryService categoryService = new CategoryService();
                    List<Category> category = new List<Category>();
                    category = categoryService.GetAllAssetCategory().ToList();
                    DataBindToMainCategory(category.Where(x => x.ParentId == 0).ToList(), mainCategoryId);
                    DataBindToSubCategory(category.Where(x => x.ParentId == mainCategoryId).ToList(), subCategoryId);
                    DataBindToAsset(Convert.ToInt64(Session["AssetId"]));
                    textBoxQuantity.Text = Convert.ToInt64(arrayParameters[3]).ToString();
                    textBoxUnitCost.Text = Convert.ToInt64(arrayParameters[4]).ToString();

                    textBoxTotalCost.Text = (Convert.ToInt64(textBoxQuantity.Text) * Convert.ToDecimal(textBoxUnitCost.Text)).ToString();
                    DisableComponents();
                }
                else
                {

                }

            }
        }

        private void DisableComponents()
        {
            dropDownListMainCategory.Enabled = false;
            dropDownListSubCategory.Enabled = false;
            dropDownListAsset.Enabled = false;
            textBoxQuantity.Enabled = false;
            textBoxUnitCost.Enabled = false;
            textBoxTotalCost.Enabled = false;
        }

        private void GetAllMainCategory()
        {
            dropDownListMainCategory.Items.Clear();
            CategoryService categoryService = new CategoryService();
            Category category = new Category();
            try
            {
                dropDownListMainCategory.DataSource = categoryService.GetAllAssetCategory().Where(x => x.ParentId == 0).ToList();

                dropDownListMainCategory.DataValueField = "CategoryId";
                dropDownListMainCategory.DataTextField = "Description";
                dropDownListMainCategory.DataBind();
            }
            catch (Exception exception)
            {
                throw;
            }
        }

        private void DataBindToMainCategory(List<Category> category, long mainCategoryId)
        {

            //category.Add((Category) categoryService.GetAssetCategoryById(Convert.ToInt64(arrayParameters[0])));

            dropDownListMainCategory.DataSource = category;
            dropDownListMainCategory.DataValueField = "CategoryId";
            dropDownListMainCategory.DataTextField = "Description";
            dropDownListMainCategory.DataBind();
            dropDownListMainCategory.SelectedValue = mainCategoryId.ToString();
        }

        private void DataBindToSubCategory(List<Category> category, long subCategoryId)
        {
            dropDownListSubCategory.Items.Clear();
            dropDownListSubCategory.DataSource = category;
            dropDownListSubCategory.DataValueField = "CategoryId";
            dropDownListSubCategory.DataTextField = "Description";
            dropDownListSubCategory.DataBind();
            dropDownListSubCategory.SelectedValue = subCategoryId.ToString();
        }

        private void DataBindToAsset(long AssetId)
        {

            AssetService assetService = new AssetService();
            List<Assets> assets = new List<Assets>();
            assets = assetService.GetAllAsset().Where(x => x.AssetId == AssetId).ToList();

        }

        private void GetOrganizationLevelList()
        {
            dropDownListOrganizationLevelList.Items.Clear();
            OrganizationLevelListService organizationLevelListService = new OrganizationLevelListService();
            List<OrganizationLevelList> organizationLevelLists = new List<OrganizationLevelList>();
            organizationLevelLists = organizationLevelListService.GetAllOrganizationLevelList().Where(x => x.OrganizationLevelMode == "B").ToList();
            dropDownListOrganizationLevelList.DataSource = organizationLevelLists;
            dropDownListOrganizationLevelList.DataValueField = "OrganizationLevelListId";
            dropDownListOrganizationLevelList.DataTextField = "Code";
            dropDownListOrganizationLevelList.DataBind();

        }

        private void GetSuppliers()
        {
            dropDownListSupplierCod.Items.Clear();
            EmployeeService EmployeeService = new EmployeeService();
            List<Employee> Employees = new List<Employee>();
            Employees = EmployeeService.GetAllEmployee().Where(x => x.EmployeeType == "Supplier").ToList();
            dropDownListSupplierCod.DataSource = Employees;
            dropDownListSupplierCod.DataValueField = "EmployeeId";
            dropDownListSupplierCod.DataTextField = "EmployeeName";
            dropDownListSupplierCod.DataBind();
        }



        protected void dropDownListMainCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            GetAllSubCategory();
        }

        protected void dropDownListSubCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            GetAssets();
        }

        protected void dropDownListOrganizationLevelList_SelectedIndexChanged(object sender, EventArgs e)
        {
            GetTransaction();
        }

        private void GetTransaction()
        {
            TransactionService transactionService = new TransactionService();
            dropDownListTransactionNo.DataSource = transactionService.GetAllTransaction().
                Where(x => x.OrganizationLevelListId == Convert.ToInt64(dropDownListOrganizationLevelList.SelectedValue) && x.TransactionDocumentCode == "PRN");
            dropDownListTransactionNo.DataTextField = "TransactionNo";
            dropDownListTransactionNo.DataValueField = "TransactionId";
            dropDownListTransactionNo.DataBind();
        }

        private void GetAllSubCategory()
        {
            dropDownListSubCategory.Items.Clear();
            CategoryService categoryService = new CategoryService();
            Category category = new Category();
            try
            {
                dropDownListSubCategory.DataSource = categoryService.GetAllAssetCategory().Where(x => x.ParentId == Convert.ToInt32(dropDownListMainCategory.SelectedValue)).ToList();

                dropDownListSubCategory.DataValueField = "CategoryId";
                dropDownListSubCategory.DataTextField = "Description";
                dropDownListSubCategory.DataBind();
            }
            catch (Exception exception)
            {
                throw;
            }
        }

        private void GetAssets()
        {
            dropDownListAsset.Items.Clear();
            AssetService assetService = new AssetService();
            Assets assets = new Assets();
            try
            {
                dropDownListAsset.DataSource = assetService.GetAllAsset().Where(x => x.AssetCategoryId == Convert.ToInt32(dropDownListSubCategory.SelectedValue)).ToList();

                dropDownListAsset.DataValueField = "AssetId";
                dropDownListAsset.DataTextField = "Description";
                dropDownListAsset.DataBind();
            }
            catch (Exception exception)
            {
                throw;
            }
        }

        protected void textBoxUnitCost_OnTextChange(object sender, EventArgs e)
        {
            try
            {
                textBoxTotalCost.Text = ((Convert.ToDecimal(textBoxUnitCost.Text) * Convert.ToInt16(textBoxQuantity.Text)).ToString());
            }
            catch (Exception)
            {

            }

        }

        protected void buttonAddItemDetails_OnClick(object sender, EventArgs e)
        {
            Session["AssetId"] = Convert.ToInt64(dropDownListAsset.SelectedValue);
            //Response.Redirect("FixedAssetItemDetailsForm.aspx?Parameter=" + assetId + ";" + Server.UrlEncode(dropDownListMainCategory.SelectedValue) + ";" + Server.UrlEncode(dropDownListSubCategory.SelectedValue) + ";" +  Server.UrlEncode(dropDownListAsset.SelectedValue) + ";" + assetQuantity);
            Response.Redirect("FixedAssetItemDetailsForm.aspx?Parameter=" + Server.UrlEncode(dropDownListAsset.SelectedValue) + ";" + Server.UrlEncode(dropDownListMainCategory.SelectedValue) + ";" + Server.UrlEncode(dropDownListSubCategory.SelectedValue) + ";" + Server.UrlEncode(dropDownListAsset.SelectedValue) + ";" + textBoxQuantity.Text + ";" + "PR" + ";" + Server.UrlEncode(dropDownListOrganizationLevelList.SelectedValue));
        }



        protected void buttonSave_OnClick(object sender, EventArgs e)
        {
            try
            {
                TransactionService transactionService = new TransactionService();
                AssetProcurementDetailsService assetProcurementDetailsService = new AssetProcurementDetailsService();
                Transaction transaction = new Transaction();
                transaction.TransactionTypeCode = Convert.ToString("ASPRO");
                transaction.TransactionDocumentCode = Convert.ToString("PRN");
                transaction.CompanyId = 1;
                transaction.OrganizationLevelListId = Convert.ToInt64(dropDownListOrganizationLevelList.SelectedValue);
                int serial = Getserial();
                ViewState["TransactionNo"] = Convert.ToString(CreateNewTransactionCode((serial + 1)));
                dropDownListTransactionNo.SelectedItem.Text = ViewState["TransactionNo"].ToString();

                //transaction.TransactionNo = "GAM/PRN/20120830/000001";
                transaction.TransactionNo = (ViewState["TransactionNo"].ToString());
                transaction.TransactionUserId = 1;
                transaction.TransactionStatus = "A";
                //transaction.TransactionDate = DateTime.Now;

                AssetProcurementDetails assetProcurementDetails = new AssetProcurementDetails();
                transactionService.AddTransaction(transaction);

                long transactionId = transactionService.GetMaxTransactionNumber();

                assetProcurementDetails.TransactionLine = Convert.ToInt16(textBoxQuantity.Text);
                for (int i = 0; i < assetProcurementDetails.TransactionLine; i++)
                {
                    assetProcurementDetails.TransactionId = transactionId;
                    assetProcurementDetails.TransactionLine = i;
                    assetProcurementDetails.AssetCode = dropDownListAsset.SelectedItem.Text;

                    assetProcurementDetails.AssetSerialCode = "";
                    assetProcurementDetails.SerialQuantity = Convert.ToInt16(textBoxQuantity.Text);
                    assetProcurementDetails.UnitPrice = Convert.ToDecimal(textBoxUnitCost.Text);
                    assetProcurementDetails.TotalPrice = Convert.ToDecimal(textBoxTotalCost.Text);
                    assetProcurementDetailsService.AddAssetProcurementDetails(assetProcurementDetails);
                }

                OrganizationLevelListAsset organizationLevelListAsset = new OrganizationLevelListAsset();
                OrganizationLevelListAssetService organizationLevelListAssetService = new OrganizationLevelListAssetService();

                organizationLevelListAsset.OrganizationLevelListId = Convert.ToInt64(dropDownListOrganizationLevelList.SelectedValue);
                organizationLevelListAsset.AssetId = Convert.ToInt64(ViewState["AssetId"]);
                organizationLevelListAsset.NoOfAssets = Convert.ToInt16(textBoxQuantity.Text);

                try
                {
                    organizationLevelListAssetService.ModifyOrganizationLevelListAssetByAssetId(organizationLevelListAsset);

                }
                catch (Exception)
                {

                }

                //Update TransactionSerial Table
                TransactionSerialService transactionSerialService = new TransactionSerialService();
                transactionSerialService.UpdateTransactionSerial("PRN");

                FlashMessage1.Message = "Successfully Saved";
                FlashMessage1.CssClass = "okmessage";
                FlashMessage1.Display();
            }
            catch (Exception)
            {


            }


        }

        private String CreateNewTransactionCode(int maxSerial)
        {


            // int maxSerial = (Convert.ToInt16(transactionSerialDomain.Serial)+1);
            string maxSerialFormated;
            maxSerialFormated = CreateNumberFormat(Convert.ToInt16(maxSerial));
            Regex regex = new Regex("-");
            string locationCode = dropDownListOrganizationLevelList.SelectedItem.Text;
            string[] arrayParameters = regex.Split(locationCode);
            String yearMonth = DateTime.Now.ToString("yyyyMM");

            string OrganizationLevelListCode = Convert.ToString(arrayParameters[0]);

            string NewTransactionCode = (OrganizationLevelListCode + "/"
                                     + "PRN" + "/"
                                     + yearMonth + "/"
                                   + maxSerialFormated);
            return NewTransactionCode;
        }

        private String CreateNumberFormat(Int16 maxSerial)
        {
            string maxSerialCode;
            if ((maxSerial / 10) == 0)
            {
                maxSerialCode = "0000" + maxSerial;
            }
            else if ((maxSerial / 100) == 0)
            {
                maxSerialCode = "000" + maxSerial;
            }
            else if ((maxSerial / 1000) == 0)
            {
                maxSerialCode = "00" + maxSerial;
            }
            else if ((maxSerial / 10000) == 0)
            {
                maxSerialCode = "0" + maxSerial;
            }
            else
            {
                maxSerialCode = maxSerial.ToString();
            }
            return maxSerialCode;
        }

        private int Getserial()
        {
            long transactionSerial = 0;
            TransactionSerialService transactionSerialService = new TransactionSerialService();

            transactionSerial = transactionSerialService.GetMaxTransactionSerialByWorkFlowDocumentCode("PRN");
            return Convert.ToInt16(transactionSerial);
        }

        protected void ButtonAdd_OnClick(object sender, EventArgs e)
        {
            EnableComponant();

        }

        protected void ButtonClear_OnClick(object sender, EventArgs e)
        {

        }

        private void EnableComponant()
        {
            dropDownListMainCategory.Enabled = true;
            dropDownListSubCategory.Enabled = true;
            dropDownListAsset.Enabled = true;
            textBoxQuantity.Enabled = true;
            textBoxUnitCost.Enabled = true;
            textBoxTotalCost.Enabled = true;
            ButtonApply.Enabled = true;
        }

        private void ClearComponent()
        {
            textBoxQuantity.Text = string.Empty;
            textBoxUnitCost.Text = string.Empty;
            textBoxTotalCost.Text = string.Empty;
        }

        protected void ButtonApply_OnClick(object sender, EventArgs e)
        {
            actionStatus = "Apply";

            tb = CreatePRNDetailsDataTable();
            DataBindToFixedAssets();


            //SetFieldsToDefault();
            ButtonApply.Enabled = false;
            ButtonAdd.Enabled = true;
        }

        private DataTable CreatePRNDetailsDataTable()
        {
            DataTable dt = new DataTable("Details");

            dt.Columns.Add("Category");
            dt.Columns.Add("AssetCode");
            dt.Columns.Add("SerialQuantity");
            dt.Columns.Add("UnitPrice");
            dt.Columns.Add("TotalPrice");

            return dt;
        }

        private void DataBindToFixedAssets()
        {

            try
            {
                DataRow dr = tb.NewRow();
                dr["Category"] = dropDownListMainCategory.SelectedItem;
                dr["AssetCode"] = dropDownListAsset.SelectedItem;
                dr["SerialQuantity"] = textBoxQuantity.Text;
                dr["UnitPrice"] = textBoxUnitCost.Text;
                dr["TotalPrice"] = textBoxTotalCost.Text;

                GridToDT(gridViewAquisitionItems);

                tb.Rows.Add(dr);
                gridViewAquisitionItems.DataSource = tb;
                gridViewAquisitionItems.DataBind();
            }
            catch (Exception ex)
            {

            }

        }

        private void GridToDT(GridView gv)
        {
            DataTable dt = new DataTable("Details");

            dt.Columns.Add("Category");
            dt.Columns.Add("AssetCode");
            dt.Columns.Add("SerialQuantity");
            dt.Columns.Add("UnitPrice");
            dt.Columns.Add("TotalPrice");

            foreach (GridViewRow row in gv.Rows)
            {
                DataRow dtrow = tb.NewRow();

                dtrow[0] = row.Cells[1].Text;
                dtrow[1] = row.Cells[2].Text;
                dtrow[2] = row.Cells[3].Text;
                dtrow[3] = row.Cells[4].Text;
                dtrow[4] = row.Cells[5].Text;


                tb.Rows.Add(dtrow);
            }

            //return dt;
        }

        protected void dropDownListTransactionNo_SelectedIndexChanged(object sender, EventArgs e)
        {
            TransactionService transactionService = new TransactionService();
            long transactionNo = Convert.ToInt64(dropDownListTransactionNo.SelectedValue);

            gridViewAquisitionItems.DataSource = transactionService.GETAssetDetailsByTransactionId(transactionNo);
            gridViewAquisitionItems.DataBind();
        }
    }
}
